﻿using System;
using System.IO;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using ArchitectingInnovation.PRISMvvM.Core.Serialization;

namespace ArchitectingInnovation.PRISMvvM.Core.Modularity
{
    public class ManifestDownloader
    {
        private HttpWebRequest _request;
        public void Download()
        {
            var manifestUri = new Uri("/AppManifest.xml", UriKind.RelativeOrAbsolute);
            _request = HttpWebRequest.CreateHttp(manifestUri);
            
            var result = _request.BeginGetResponse(OnResponse, null);
            

        }

        public ApplicationManifest Manifest { get; private set; }

        public bool Done { get; private set; }

        public void OnResponse(IAsyncResult result)
        {
            string xml = null;
            var response = _request.EndGetResponse(result);
            using(var stream = response.GetResponseStream())
            {
                using(var rdr = new StreamReader(stream))
                {
                    xml = rdr.ReadToEnd();
                }
            }
            if (!String.IsNullOrEmpty(xml))
            {
                try
                {
                    this.Manifest = new XmlSerializer().Deserialize<ApplicationManifest>(xml);
                }
                catch
                {
                }
                this.Done = true;
            }
        }
    }
}
